<template>
  <div class="box">
    <h3>修改登录密码</h3>
    <el-form label-width="100px" :model="pwd" :rules="rules" ref="pwdForm" class="box-body mgt20">
      <el-col :span="8">
        <el-form-item prop="current" label="当前密码">
          <el-input type="password" v-model="pwd.current"></el-input>
        </el-form-item>
        <el-form-item prop="newPwd" label="新密码">
          <el-input type="password" v-model="pwd.newPwd"></el-input>
        </el-form-item>
        <el-form-item prop="newPwdCopy" label="确认新密码">
          <el-input type="password" v-model="pwd.newPwdCopy"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="pwd.updating" @click="updatePwd()">更新</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import { Member } from '@/store/api'
export default {
  data() {
    let validatePwdCopy = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.pwd.newPwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      pwd: {
        current: null,
        newPwd: null,
        newPwdCopy: null,
        updating: false
      },
      rules: {
        current: [
          { required: true, message: '当前密码不能为空', trigger: 'blur' }
        ],
        newPwd: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 8, max: 16, message: '长度在8到16位之间', trigger: 'blur' }
        ],
        newPwdCopy: [
          { validator: validatePwdCopy, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updatePwd() {
      this.$refs['pwdForm'].validate(valid => {
        if (valid) {
          this.pwd.updating = true
          const payload = Object.assign({}, this.pwd)
          Member.updatePwd(payload).then(() => {
            this.pwd.updating = false
            this.$message({
              showClose: true,
              message: '登录密码已更新',
              type: 'success'
            })
          }).catch(_ => {
            this.pwd.updating = false
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
